package com.code.translate.controllers;

import com.code.translate.configs.TranslateConfig;
import com.code.translate.enums.ImageTranslateToolEnum;
import com.code.translate.utils.RandomUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author ggh
 * @date 2022/7/20
 */
@Slf4j
@RestController
public class TranslateImgController {
    @Autowired
    private TranslateConfig translateConfig;

    /**
     * 图片翻译接口
     *
     * @param image 待翻译图片
     * @return
     */
    @RequestMapping("/translateImage")
    public String translateImage(@RequestParam("image") MultipartFile image, @RequestParam(value = "type", required = false) Integer type) {
        List<Integer> values = ImageTranslateToolEnum.getValues();

        if (CollectionUtils.isEmpty(values)) {
            log.info("没有配置图片翻译工具,翻译失败");
            return null;
        }

        try {
            // 标记是否固定使用某个翻译工具
            boolean fixed = true;
            if (type == null || type == 0) {
                fixed = false;
            }
            for (int i = 0; i < translateConfig.getTranslateTimes(); i++) {
                if (!fixed) {
                    type = values.get(RandomUtils.nextInt(values.size()));
                }

                ImageTranslateToolEnum translateTool = ImageTranslateToolEnum.parse(type);
                if (translateTool == null) {
                    log.info("未找到翻译工具");
                    return null;
                }

                log.info("使用：" + translateTool.getMsg());

                String result = translateTool.getImageTranslatePlugin().translateImageByStream(image.getInputStream());
                if (StringUtils.isEmpty(result)) {
                    if (!fixed) {
                        // 如果随即翻译失败，则剔除该插件后继续随机选择
                        values.remove(type);
                    }
                } else {
                    return result;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
